<template>
  <div class="resources-page">
    <div class="video-container">
      <!-- 视频播放器 -->
      <div class="player-wrapper">
        <video
          ref="videoPlayer"
          class="video-player"
          :src="currentVideo?.url"
          :poster="movieDetail?.poster"
          controls
          controlslist="nodownload"
          @timeupdate="handleTimeUpdate"
          @play="handlePlay"
          @pause="handlePause"
          @ended="handleEnded"
        >
          您的浏览器不支持视频播放
        </video>

        <!-- 付费提示遮罩 -->
        <div v-if="showPayTip" class="pay-tip-overlay">
          <div class="pay-tip-content">
            <el-icon :size="60" color="#409EFF">
              <Lock />
            </el-icon>
            <h3 class="mt-4 text-xl">此为付费视频</h3>
            <p class="mt-2 text-gray-300">
              观看完整内容需支付 <span class="text-yellow-400">{{ movieDetail?.paymentAmount || 0 }}</span> 金币
            </p>
            <p class="text-sm text-gray-400 mt-2">
              已观看 {{ freeMinutes }} 分钟免费内容
            </p>
            <div class="mt-6 flex gap-4">
              <el-button type="primary" size="large" @click="handleBuyMovie">
                立即购买
              </el-button>
              <el-button size="large" @click="navigateTo('/')">
                返回首页
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 视频信息和选集 -->
      <div class="video-info-section">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="视频信息" name="video">
            <template #label>
              <span class="flex items-center gap-2">
                视频
                <span class="text-yellow-400 text-xs flex items-center">
                  <i class="i-carbon-view mr-1"></i>
                  {{ movieDetail?.pv?.pv || 0 }}
                </span>
              </span>
            </template>

            <!-- 影片基本信息 -->
            <div class="movie-basic-info">
              <div class="flex gap-4">
                <el-image
                  :src="movieDetail?.poster"
                  class="w-20 h-28 rounded-lg"
                  fit="cover"
                >
                  <template #error>
                    <div class="w-20 h-28 bg-gray-700 rounded-lg flex items-center justify-center">
                      <el-icon :size="30" color="#999">
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>

                <div class="flex-1">
                  <h1 class="text-2xl font-bold text-white mb-2">
                    {{ movieDetail?.title }}
                  </h1>

                  <!-- 评分 -->
                  <div class="flex items-center gap-2 mb-2">
                    <el-rate
                      v-model="userRating"
                      :disabled="userRating > 0"
                      allow-half
                      @change="handleRateChange"
                    />
                    <span class="text-yellow-400">
                      {{ movieDetail?.rating ? movieDetail.rating.toFixed(1) : '暂无评分' }}
                    </span>
                  </div>

                  <div class="text-sm text-gray-400 space-y-1">
                    <p>{{ movieDetail?.year }}</p>
                    <p v-if="movieDetail?.countries">
                      {{ movieDetail.countries }}
                    </p>
                    <p v-if="movieDetail?.languages">
                      {{ movieDetail.languages }}
                    </p>
                  </div>

                  <div v-if="movieDetail?.tags" class="flex gap-2 mt-2">
                    <el-tag
                      v-for="(tag, index) in movieDetail.tags.split(',')"
                      :key="index"
                      size="small"
                      type="info"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
              </div>

              <!-- 剧情简介 -->
              <div v-if="movieDetail?.introduction" class="mt-6">
                <h2 class="text-lg font-semibold mb-3 text-white">节目简介</h2>
                <p class="text-gray-300 leading-relaxed">
                  {{ movieDetail.introduction }}
                </p>
              </div>

              <!-- 选集列表 -->
              <div v-if="episodes.length > 0" class="mt-6">
                <h2 class="text-lg font-semibold mb-3 text-white">选集</h2>
                <div class="grid grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
                  <el-button
                    v-for="episode in episodes"
                    :key="episode.videoId"
                    :type="currentEpisodeId === episode.videoId ? 'primary' : 'default'"
                    size="small"
                    @click="selectEpisode(episode)"
                  >
                    {{ episode.title || `第${episode.sort}集` }}
                  </el-button>
                </div>
              </div>

              <!-- 演员阵容 -->
              <div v-if="movieDetail?.actors && movieDetail.actors.length > 0" class="mt-6">
                <h2 class="text-lg font-semibold mb-3 text-white">相关演员</h2>
                <div class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
                  <div
                    v-for="actor in movieDetail.actors"
                    :key="actor.actorId"
                    class="text-center"
                  >
                    <el-avatar :src="actor.avatar" :size="80" />
                    <p class="text-sm mt-2 text-white">{{ actor.name }}</p>
                    <p class="text-xs text-gray-400">{{ actor.role || actor.profession }}</p>
                  </div>
                </div>
              </div>

              <!-- 相关推荐 -->
              <div v-if="relatedMovies.length > 0" class="mt-6">
                <h2 class="text-lg font-semibold mb-3 text-white">相关推荐</h2>
                <div class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
                  <MovieCard
                    v-for="movie in relatedMovies"
                    :key="movie.movieId"
                    :movie="movie"
                  />
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock, Picture } from '@element-plus/icons-vue'

const route = useRoute()
const userStore = useUserStore()

// 状态
const activeTab = ref('video')
const videoPlayer = ref()
const showPayTip = ref(false)
const userRating = ref(0)
const currentEpisodeId = ref<number | null>(null)
const currentVideo = ref<any>(null)
const movieDetail = ref<any>(null)
const episodes = ref<any[]>([])
const relatedMovies = ref<any[]>([])
const hasPurchased = ref(false)
const freeMinutes = ref(0)
const playTime = ref(0)

// 获取影片详情
const fetchMovieDetail = async () => {
  try {
    const data = await $fetch(`/dev-api/movie/basics/${route.params.id}`)
    if (data.code === 200) {
      movieDetail.value = data.data
    }
  } catch (error) {
    console.error('获取影片详情失败:', error)
  }
}

// 获取集数列表
const fetchEpisodes = async () => {
  try {
    const data = await $fetch('/dev-api/movie/video/list', {
      params: {
        movieId: route.params.id,
        resourceId: route.query.rid,
        resources: route.query.rtype
      }
    })

    if (data.code === 200) {
      episodes.value = data.rows || []

      // 设置当前集数
      if (route.query.rid) {
        currentEpisodeId.value = Number(route.query.rid)
        const episode = episodes.value.find(e => e.videoId === currentEpisodeId.value)
        if (episode) {
          currentVideo.value = episode
        }
      } else if (episodes.value.length > 0) {
        currentVideo.value = episodes.value[0]
        currentEpisodeId.value = episodes.value[0].videoId
      }
    }
  } catch (error) {
    console.error('获取集数列表失败:', error)
  }
}

// 获取相关推荐
const fetchRelatedMovies = async () => {
  try {
    const data = await $fetch('/dev-api/movie/basics/list', {
      params: {
        columnValue: route.params.columnValue,
        pageSize: 10,
        notId: route.params.id
      }
    })

    if (data.code === 200) {
      relatedMovies.value = data.rows || []
    }
  } catch (error) {
    console.error('获取相关推荐失败:', error)
  }
}

// 检查购买状态
const checkPurchaseStatus = async () => {
  if (!isLoggedIn.value) return

  try {
    const data = await $fetch(`/dev-api/member/movie/buyStatus`, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      params: {
        movieBasicsId: route.params.id
      }
    })

    if (data.code === 200) {
      hasPurchased.value = data.data || false
    }
  } catch (error) {
    console.error('检查购买状态失败:', error)
  }
}

// 获取用户评分
const fetchUserRating = async () => {
  if (!isLoggedIn.value) return

  try {
    const data = await $fetch('/dev-api/member/rate', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      params: {
        movieBasicsId: route.params.id
      }
    })

    if (data.code === 200 && data.data) {
      userRating.value = data.data.rate / 2 // 后端是10分制，前端是5分制
    }
  } catch (error) {
    console.error('获取用户评分失败:', error)
  }
}

// 选择集数
const selectEpisode = (episode: any) => {
  currentVideo.value = episode
  currentEpisodeId.value = episode.videoId
  playTime.value = 0

  // 更新URL
  navigateTo({
    path: route.path,
    query: {
      rid: episode.videoId,
      rtype: episode.resources
    }
  })

  // 重新加载视频
  nextTick(() => {
    if (videoPlayer.value) {
      videoPlayer.value.load()
      videoPlayer.value.play()
    }
  })
}

// 处理时间更新
const handleTimeUpdate = () => {
  if (!videoPlayer.value) return

  playTime.value = videoPlayer.value.currentTime

  // 如果是付费视频且未购买，检查是否超过免费时长
  if (movieDetail.value?.isPay === 1 && !hasPurchased.value) {
    const freeSeconds = (movieDetail.value.freeDuration || 0) * 60
    freeMinutes.value = Math.floor(playTime.value / 60)

    if (playTime.value >= freeSeconds) {
      videoPlayer.value.pause()
      showPayTip.value = true
    }
  }
}

// 处理播放
const handlePlay = () => {
  // 可以记录播放行为
}

// 处理暂停
const handlePause = () => {
  // 可以记录暂停行为
}

// 处理播放结束
const handleEnded = () => {
  // 自动播放下一集
  const currentIndex = episodes.value.findIndex(e => e.videoId === currentEpisodeId.value)
  if (currentIndex >= 0 && currentIndex < episodes.value.length - 1) {
    selectEpisode(episodes.value[currentIndex + 1])
  }
}

// 处理评分
const handleRateChange = async (value: number) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    userRating.value = 0
    return
  }

  try {
    const data = await $fetch('/dev-api/member/rate', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: {
        movieBasicsId: route.params.id,
        rate: value * 2 // 转换为10分制
      }
    })

    if (data.code === 200) {
      ElMessage.success('评分成功')
      // 更新影片评分
      if (data.data) {
        movieDetail.value.rating = data.data.rate
      }
    }
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '评分失败')
    userRating.value = 0
  }
}

// 购买影片
const handleBuyMovie = async () => {
  if (!userStore.isLoggedIn) {
    navigateTo('/login')
    return
  }

  ElMessageBox.confirm(
    `确定要支付 ${movieDetail.value?.paymentAmount || 0} 金币购买此影片吗？`,
    '购买确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const data = await $fetch('/dev-api/member/movie/buy', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${userStore.token}`
        },
        body: {
          movieBasicsId: route.params.id
        }
      })

      if (data.code === 200) {
        ElMessage.success('购买成功')
        hasPurchased.value = true
        showPayTip.value = false

        // 继续播放
        if (videoPlayer.value) {
          videoPlayer.value.play()
        }
      }
    } catch (error: any) {
      ElMessage.error(error.data?.msg || '购买失败')
    }
  }).catch(() => {
    // 取消购买
  })
}

// 初始化
onMounted(async () => {
  await Promise.all([
    fetchMovieDetail(),
    fetchEpisodes(),
    fetchRelatedMovies(),
    checkPurchaseStatus(),
    fetchUserRating()
  ])
})

// SEO
useSeoMeta({
  title: `${movieDetail.value?.title || ''}在线观看`,
  description: movieDetail.value?.introduction || ''
})
</script>

<style scoped>
.resources-page {
  min-height: 100vh;
  background-color: #0f0f0f;
  padding-top: 64px;
}

.video-container {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

@media (min-width: 1024px) {
  .video-container {
    grid-template-columns: 1fr 400px;
  }
}

.player-wrapper {
  position: relative;
  background-color: #000;
  aspect-ratio: 16 / 9;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.pay-tip-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.pay-tip-content {
  text-align: center;
  padding: 40px;
  color: white;
}

.video-info-section {
  padding: 20px;
  background-color: rgba(31, 41, 55, 0.8);
  border-radius: 8px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.movie-basic-info {
  color: #e5e7eb;
}

:deep(.el-tabs__item) {
  color: #999;
}

:deep(.el-tabs__item.is-active) {
  color: #fff;
}

:deep(.el-tabs__active-bar) {
  background: #10b981;
}

:deep(.el-button--default) {
  background-color: rgba(55, 65, 81, 0.5);
  border-color: rgba(55, 65, 81, 0.8);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-button--default:hover) {
  background-color: rgba(55, 65, 81, 0.7);
  border-color: #10b981;
}

:deep(.el-button--primary) {
  background-color: #10b981;
  border-color: #10b981;
}
</style>
